import { sendMobileCode } from '@/api/flow/auth';

export default {
  data() {
    return {
      // send code
      isSendCode: false,
      codeText: 'Verification code sent',
      interval: null,
      time: 60
    };
  },

  beforeDestroy() {
    window.clearInterval(this.interval);
  },

  computed: {
    codeText() {
      return this.isSendCode ? 'Verification code sent' : 'Send Verification Code';
    }
  },

  methods: {
    resetCodeStatus() {
      this.isSendCode = false;

      this.time = 60;

      this.codeText = 'Verification code sent';

      window.clearInterval(this.interval);
    },
    sendCode(f = 'phone', data) {
      const fields = Array.isArray(f) ? f : [f];

      this.form.validateFields(fields, (errors, values) => {
        if (!errors) {
          this.isSendCode = true;

          sendMobileCode(data)
            .then(() => {
              this.interval = window.setInterval(() => {
                this.codeText = `${this.time}s resend verification`;
                if (this.time-- <= 0) {
                  this.time = 60;
                  this.codeText = 'Resend verification code';
                  this.isSendCode = false;
                  window.clearInterval(this.interval);

                  return false;
                }
              }, 1000);
            })
            .catch(() => {
              this.time = 60;
              this.isSendCode = false;
            });
          // this.isSendCode = true;
          // const phone = this.form.getFieldValue(field);
          // sendMobileCode(phone)
          //   .catch(() => {
          //     this.isSendCode = false;
          //   });
        }
      });
    }
  }
};
